<link rel="stylesheet" href="style.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<?php

include_once 'config.php';
global $extensions;

$get = array_merge($_GET,$_POST);

$file = @$_FILES["file"];
$dir = $get["dir"];

$linkback = '<a href="upload.php?dir='.$dir.'">nazad</a>';

if($file) {
	if($file["error"]) {
		die($file["error"]."<br />$linkback");
	}else{
		$rgx = '/\.'.implode('$|\.', $extensions).'$/i';
		if (!preg_match($rgx, $file["name"])) {
			die("Morate odabrati sliku nekog od sledećih tipova: ".implode(", ", $extensions)."<br />$linkback");
		}
		$destination = $_SERVER["DOCUMENT_ROOT"].$dir."/".$file["name"];
		$s = move_uploaded_file($file["tmp_name"], $destination);
		if($s) {
			// resize to max_dimensions
			image_resize($destination);
			chmod($destination, 0777);
			
			echo "Slika je poslata.<br />$linkback";
			echo '
				<script type="text/javascript">
					parent.ImagePickerReload();
				</script>
			';
		}else{
			echo "Greška. Slika nije poslata.<br />$linkback";
		}
	}
}else{
	?>
	<style>
		body {
			margin:0;
			padding:0;
			background:transparent;
		}
	</style>
	<form action="upload.php" method="post" enctype="multipart/form-data">
		<input type="hidden" name="dir" value="<?php echo $dir; ?>" />
		<input type="file" name="file" id="file" />
		
		<input type="submit" value="Pošalji" />
	
	</form>
	
	 <?php
}


function image_resize($path) {
	global $extensions, $max_dimensions;
	if(file_exists($path)) {
		$ext = strtolower(substr($path, strrpos($path,".")+1));
		$ext_eval = $ext=="jpg" ? "jpeg" : $ext;
		$rgx = '/\.'.implode('$|\.', $extensions).'$/i';
		
		if(preg_match($rgx,$path)) {
			eval('$img = imagecreatefrom'.$ext_eval.'(\''.$path.'\');');
			if($img) {
				$width = imagesx($img); 
				$height = imagesy($img);
				$width1 = $width; $height1 = $height;
				
				if($height>$width) {
					$max_dimensions = array_reverse($max_dimensions);
				}
				
				if($height > $max_dimensions[1]) {
					$width = $max_dimensions[1]*$width/$height;
					$height = $max_dimensions[1];
				}
				if ($width > $max_dimensions[0]) {
					$height = $max_dimensions[0]*$height/$width;
					$width = $max_dimensions[0];
				}
				$img2 = imagecreatetruecolor($width,$height);
				imagecopyresized($img2,$img,0,0,0,0,$width,$height,$width1,$height1);
				
				eval('image'.$ext_eval.'($img2,$path);');
			}
		}
	}
}

?>